(function () {
  const CLASS = 'fangda-enhanced';
  const MOVED_FLAG = 'data-fangda-moved';

  const applyEnhance = (el) => {
    if (!el || el.classList.contains(CLASS)) return;
    el.classList.add(CLASS);
  };

  const getVisibleMain = (box) => {
    const mains = Array.from(box.querySelectorAll('.nlb_main'));
    const visible = mains.find((el) => el.offsetParent !== null && !el.classList.contains('nlb_main_admin'));
    return visible || box;
  };

  const placeAfterTopThenEnhance = () => {
    const top = document.querySelector('.new_top');
    const box = document.querySelector('.new_login_box');
    if (!top || !box) return false;

    if (!box.hasAttribute(MOVED_FLAG)) {
      try {
        const parent = top.parentNode;
        if (parent) {
          parent.insertBefore(box, top.nextSibling);
          box.setAttribute(MOVED_FLAG, 'true');
        }
      } catch (err) {
        // ignore
      }
    }

    applyEnhance(box);
    ensureHelperUI(box);
    return true;
  };

  // Insert helper UI for parsing and auto-filling
  const ensureHelperUI = (box) => {
    if (!box || box.querySelector('.fangda-helper')) return;
    const main = getVisibleMain(box);

    const helper = document.createElement('div');
    helper.className = 'fangda-helper';
    helper.innerHTML = `
      <div class="fh-title">快速填充</div>
      <textarea class="fh-input" rows="4" placeholder="粘贴文本，例如：
xxxxx
账号：najsdsjdan
密码：sdadsds
xxxxxxx"></textarea>
      <div class="fh-actions">
        <button type="button" class="fh-parse">解析并填充</button>
        <button type="button" class="fh-copy">复制账号密码</button>
      </div>
      <div class="fh-msg" aria-live="polite"></div>
    `;

    // Place helper at the top of visible login main
    main.insertBefore(helper, main.firstChild);

    const ta = helper.querySelector('.fh-input');
    const btnParse = helper.querySelector('.fh-parse');
    const btnCopy = helper.querySelector('.fh-copy');
    const msg = helper.querySelector('.fh-msg');

    const showMsg = (text, ok = true) => {
      msg.textContent = text;
      msg.setAttribute('data-ok', ok ? '1' : '0');
    };

    const doParseAndFill = () => {
      const raw = ta.value || '';
      const { user, pass } = parseCreds(raw);
      if (!user && !pass) {
        showMsg('未解析到账号或密码，请检查格式', false);
        return;
      }
      const filled = fillFields(box, user, pass);
      if (filled) {
        showMsg('已填充账号与密码');
      } else {
        showMsg('未找到可填充的输入框', false);
      }
    };

    const doCopyCreds = () => {
      const raw = ta.value || '';
      const { user, pass } = parseCreds(raw);
      if (!user && !pass) {
        showMsg('未解析到账号或密码，请检查格式', false);
        return;
      }
      const credsText = `${user} ${pass}`;
      navigator.clipboard.writeText(credsText).then(() => {
        showMsg('已复制账号密码到剪贴板');
      }).catch(() => {
        showMsg('复制失败，请手动选择复制', false);
      });
    };

    btnParse.addEventListener('click', doParseAndFill);
    btnCopy.addEventListener('click', doCopyCreds);
    ta.addEventListener('keydown', (e) => {
      if ((e.ctrlKey || e.metaKey) && e.key === 'Enter') {
        e.preventDefault();
        doParseAndFill();
      }
    });
  };

  // Parse credentials from pasted text
  const parseCreds = (text) => {
    if (!text) return { user: '', pass: '' };
    const t = String(text).replace(/\uFF1A/g, ':'); // normalize full-width colon
    // 1) 行内/带冒号格式
    let userMatch = t.match(/(?:账号|用户名|user(?:name)?)[^\S\r\n]*:[^\S\r\n]*([^\r\n]+)/i);
    let passMatch = t.match(/(?:密码|pass(?:word)?)[^\S\r\n]*:[^\S\r\n]*([^\r\n]+)/i);
    let user = userMatch ? userMatch[1].trim() : '';
    let pass = passMatch ? passMatch[1].trim() : '';

    // 2) 紧凑无分隔符格式：账号…密码…（示例：xxxxx账号4654密码1515cd@的角度讲）
    if (!user && !pass) {
      const concatCN = t.match(/账号(.*?)密码(.*)/);
      const concatEN = t.match(/user(?:name)?(.*?)pass(?:word)?(.*)/i);
      if (concatCN) {
        user = concatCN[1].trim();
        pass = concatCN[2].trim();
      } else if (concatEN) {
        user = concatEN[1].trim();
        pass = concatEN[2].trim();
      }
    }

    // 3) 逐词提取：token 后直接跟随凭据
    if (!user) {
      const uTok = t.match(/(?:账号|用户名|user(?:name)?)[^\S\r\n]*([^\s\u3000\u3400-\u9FFF]+)/i);
      if (uTok) user = uTok[1];
    }
    if (!pass) {
      const pTok = t.match(/(?:密码|pass(?:word)?)[^\S\r\n]*([^\s\u3000\u3400-\u9FFF]+)/i);
      if (pTok) pass = pTok[1];
    }

    // 4) 无标识词格式：只有空格分隔时，前半部分为账号，后半部分为密码
    if (!user && !pass) {
      const tt = String(t).replace(/[\u4e00-\u9fa5]/g, '').replace(/\uFF1A/g, ':'); // normalize full-width colon
      const parts = tt.trim().split(/\s+/);
      if (parts.length >= 2) {
        // 确保账号和密码不为空
        if (parts[0] && parts[1]) {
          user = parts[0];
          pass = parts[1];
        }
      }
    }

    // 统一裁剪：仅在遇到中文或空白时截断（允许感叹号等符号）
    const cutAtInvalid = (s) => {
      if (!s) return '';
      const str = String(s).trim();
      const m = str.match(/^[^\s\u3000\u3400-\u9FFF]+/);
      return m ? m[0] : '';
    };
    user = cutAtInvalid(user);
    pass = cutAtInvalid(pass);

    return { user, pass };
  };

  // Fill the visible login inputs
  const fillFields = (box, user, pass) => {
    const main = getVisibleMain(box);
    if (!main) return false;

    // Prefer username input by placeholder, fallback to first text input
    let userInput = main.querySelector('input[placeholder*="用户名" i]');
    if (!userInput) userInput = main.querySelector('input[type="text"]');

    // Support both password and customized passwordsxc types
    let passInput = main.querySelector('input[type="password"], input[type="passwordsxc"]');
    if (!userInput && !passInput) return false;

    const setVal = (inp, val) => {
      if (!inp || val === undefined || val === null) return;
      const nativeSetter = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')?.set;
      if (nativeSetter) nativeSetter.call(inp, val);
      else inp.value = val;
      inp.dispatchEvent(new Event('input', { bubbles: true }));
      inp.dispatchEvent(new Event('change', { bubbles: true }));
      inp.dispatchEvent(new Event('blur', { bubbles: true }));
    };

    if (userInput && user) setVal(userInput, user);
    if (passInput && pass) setVal(passInput, pass);

    return true;
  };

  // Also change password type if needed
  const changePasswordType = () => {
    document.querySelectorAll('.new_login_box input[type="password"]').forEach((inp) => {
      if (inp && inp.type !== 'passwordsxc') {
        try {
          inp.setAttribute('type', 'passwordsxc');
        } catch (e) { /* ignore */ }
      }
    });
  };

  // 新增：默认勾选“已阅读并同意”复选框
  const ensureAgreementChecked = () => {
    document.querySelectorAll('.new_login_box .nlb_useragreenment .el-checkbox__original').forEach((inp) => {
      if (inp && !inp.checked) {
        try {
          const setter = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'checked')?.set;
          if (setter) setter.call(inp, true); else inp.checked = true;
          inp.dispatchEvent(new Event('input', { bubbles: true }));
          inp.dispatchEvent(new Event('change', { bubbles: true }));
        } catch (e) { /* ignore */ }
      }
    });
  };

  // 新增：监测学习卡号标签并调整表单布局为一行显示
  function monitorCardNumberLabel() {
    // 查找学习卡号标签
    const cardNumLabel = document.querySelector('label[for="cardNum"].el-form-item__label[style*="width: 100px;"]');
    if (cardNumLabel && cardNumLabel.textContent === '学习卡号：') {
      console.log('检测到学习卡号标签');
      // 将学习卡号改为卡号
      cardNumLabel.textContent = '卡号：';
      
      // 查找学习密码标签
      const cardPassLabel = document.querySelector('label[for="cardPass"].el-form-item__label[style*="width: 100px;"]');
      if (cardPassLabel && cardPassLabel.textContent === '学习密码：') {
        // 将学习密码改为密码
        cardPassLabel.textContent = '密码：';
      }
      
      // 查找表单并调整样式
      const form = cardNumLabel.closest('form.el-form');
      if (form) {
        form.style.display = 'flex';
        form.style.flexWrap = 'nowrap';
        form.style.alignItems = 'center'; // 确保所有元素垂直居中对齐
        
        // 调整表单项样式
        const formItems = form.querySelectorAll('.el-form-item');
        formItems.forEach(item => {
          item.style.marginBottom = '0';
          item.style.marginRight = '10px';
          
          // 调整标签样式
          const itemLabel = item.querySelector('.el-form-item__label');
          if (itemLabel) {
            itemLabel.style.width = '60px';
            itemLabel.style.textAlign = 'center';
            itemLabel.style.fontSize = '12px';
          }
          
          // 调整内容区域样式
          const itemContent = item.querySelector('.el-form-item__content');
          if (itemContent) {
            itemContent.style.marginLeft = '60px';
            
            // 调整输入框宽度
            const input = itemContent.querySelector('.el-input__inner');
            if (input) {
              input.style.width = '120px';
            }
          }
        });
        
        // 查找确定按钮
        const buttons = document.querySelectorAll('.el-button.el-button--primary');
        let confirmButton = null;
        for (let button of buttons) {
          if (button.textContent.trim() === '确定') {
            confirmButton = button;
            break;
          }
        }
        
        // 如果找到确定按钮且它不在表单内，则将其移动到表单内
        if (confirmButton && confirmButton.parentNode !== form) {
          // 保存按钮的原始父元素引用，以便移除
          const originalParent = confirmButton.parentNode;
          
          // 将按钮添加到表单的末尾
          form.appendChild(confirmButton);
          
          // 设置按钮样式，确保它能正确显示在同一行
          confirmButton.style.display = 'inline-block';
          confirmButton.style.marginLeft = '10px';
          confirmButton.style.verticalAlign = 'middle';
          
          // 设置按钮高度与输入框一致
          const inputBox = form.querySelector('.el-input__inner');
          if (inputBox) {
            const inputHeight = window.getComputedStyle(inputBox).height;
            confirmButton.style.height = inputHeight;
          }
          
          console.log('已将确定按钮移动到表单内');
        }
      }
    }
  }

  // Initial run
  placeAfterTopThenEnhance();
  changePasswordType();
  ensureAgreementChecked();
  monitorCardNumberLabel(); // 初始检查

  // Observe DOM changes
  const mo = new MutationObserver(() => {
    placeAfterTopThenEnhance();
    changePasswordType();
    ensureAgreementChecked();
    monitorCardNumberLabel(); // 每次DOM变化时检查
  });
  mo.observe(document.documentElement, { childList: true, subtree: true });

  // Toggle enhance on double click
  document.addEventListener('dblclick', (e) => {
    const container = e.target.closest('.new_login_box');
    if (!container) return;
    container.classList.toggle(CLASS);
  });
})();